package com.lzp.java.concurrent.flowcontrol.condition;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lzp
 * @Description: 演示Condition基本方法使用
 * @date 2021/3/6
 */
public class ConditionDemo {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    void testAwait() {
        lock.lock();
        try {
            System.out.println("开始等待。。。");
            condition.await();
            System.out.println("结束等待。。。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void testSignal() {
        lock.lock();
        try {
            System.out.println("唤醒其他等待线程");
            condition.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ConditionDemo demo = new ConditionDemo();
        // 启用新的线程用来唤醒主线程
        new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                demo.testSignal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        // 调用await主线程阻塞。。
        demo.testAwait();
    }
}
